package com.ytc.controller;

import com.ytc.model.*;
import com.ytc.service.AuthorService;
import com.ytc.service.BookshelfService;
import com.ytc.service.UserService;
import com.ytc.util.BookShelfPageUtil;
import com.ytc.util.BookShelfPageUtilHelper;
import com.ytc.util.Md5Util;
import com.ytc.util.UserUtil;
import javafx.application.Application;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private AuthorService authorService;
    @Autowired
    private BookshelfService bookshelfService;

    /**
     * 跳转会员充值页面
     * @param request
     * @return
     */
    @RequestMapping("toVip")
    public String toVip(HttpServletRequest request, Model model) throws ParseException {
        //查询用户是否为vip
        User user = UserUtil.getUser(request);
        if(user!=null){
            //查询vip
            Integer rid = userService.isOrNotVip(user.getUId());
            if(rid==2){//是vip
                //查询到期时间
                Vip vip = userService.queryVip(user.getUId());
                if(vip==null){//该用户不是vip
                    model.addAttribute("vipFlag","0");//不是vip
                }else {
                    if(UserUtil.vipIsOrNotDue(vip.getVDuetime())){
                        model.addAttribute("vipFlag","1");//是vip，但vip过期了
                        model.addAttribute("dt",vip.getVDuetime());
                        //修改用户的权限
                        userService.updateRole(user.getUId(),2);
                    }else {//是vip，并且vip没到期
                        model.addAttribute("vipFlag","2");
                        model.addAttribute("dt",vip.getVDuetime());
                    }
                }
            }else if(rid==3){//是读者
                model.addAttribute("vipFlag","0");//不是vip
            }else if(rid==4){//是管理员
                model.addAttribute("vipFlag","3");//管理员
            }else {
                model.addAttribute("vipFlag","0");
            }
        }else {
            return "redirect:/user/toLoginReader";
        }
        return "user/payVip";
    }

    /**
     * 新增vip,若是会员不用新增，把会员时间延长
     * @return
     */
    @RequestMapping("returnUrl")
    public String returnUrl(double total_amount,HttpServletRequest request){
        User user = UserUtil.getUser(request);
        //判断用户是否为vip
        if (user!=null){
            //查询vip
            Integer rid = userService.isOrNotVip(user.getUId());
            if(rid==2){//是vip
                //直接新增对应的天数
                userService.updateDueTimeByMoney(total_amount,user.getUId());
            }else if(rid==3||rid==1){//读者和普通用户
                //修改用户权限
                userService.updateRole(user.getUId(),1);
                //新增vip
                userService.addVipByMoney(total_amount,user.getUId());
            }
        }

        return "redirect:/user/toVip";
    }


    /*作者去登录，跳转到作者登录页面*/
    @RequestMapping("toLoginAuthor")
    public String toLoginAuthor(){
        return "userLogin/authorLogin";
    }

    /*读者去登录，跳转到读者登录页面*/
    @RequestMapping("toLoginReader")
    public String toLoginReader(){
        return "userLogin/readerLogin";
    }

    /*作者去注册，跳转到作者注册页面*/
    @RequestMapping("toRegisterAuthor")
    public String toRegisterAuthor(){
        return "userLogin/authorRegister";
    }

    /*读者注册成为用户*/
    @RequestMapping("toRegisterUser")
    public String toRegisterUser(){
        return "userLogin/readerRegister";
    }

    /*柴晓颖：用户登录*/
    @RequestMapping("userLogin")
    @ResponseBody
    public String userLogin(User user, HttpServletRequest request){
        //通过用户名查询用户
        User userRes = userService.queryUserByName(user.getUName());
        if(userRes == null){
            return "1";//用户不存在，请注册
        }else {
            String md5 = Md5Util.getMd516(user.getUPwd()+userRes.getUSalt());
            String md532 = Md5Util.getMd532(md5);
            if(!md532.equals(userRes.getUPwd())){
                return "2"; //密码错误
            }
        }
        ServletContext application = request.getSession().getServletContext();
        application.setAttribute("user",userRes);
//        request.getSession().setAttribute("user",userRes);
        return "success";
    }

    /*柴晓颖：用户注册*/
    @RequestMapping("addUser")
    @ResponseBody
    public String addUser(User user){
        System.out.println(user);
        //先查询用户名是否已被注册
        User userRes = userService.queryUserByName(user.getUName());
        if (userRes != null){
            //说明该名字已有用户
            return "1";
        }else {
            //新增用户，在impl
            userService.addUser(user);
            return "success";
        }
    }

    //柴晓颖：用户退出登录
    @RequestMapping("removeUser")
    public String removeUser(HttpServletRequest request){
        request.getSession().getServletContext().removeAttribute("user");
        return "redirect:/moyue";
    }

    @RequestMapping("queryUserList")
    @ResponseBody
    public List<User> queryUserList() {
        return userService.queryUserList();
    }

    //柴晓颖：跳转关于墨阅页面
    @RequestMapping("agreement")
    public String agreement(){
        return "first/agreement";
    }
    @RequestMapping("left")
    public String left(){
        return "first/left";
    }
    @RequestMapping("top")
    public String top(){
        return "first/top";
    }
    @RequestMapping("agreement1")
    public String agreement1(){
        return "first/agreement1";
    }
    @RequestMapping("agreement2")
    public String agreement2(){
        return "first/agreement2";
    }
    @RequestMapping("agreement3")
    public String agreement3() {
        return "first/agreement3";
    }

    /**
     * 高媛：跳转到个人中心页面
     * @return
     */
    @RequestMapping("toPersonCenter")
    public String toPersonCenter(HttpServletRequest request,Model model){
        User user = (User) request.getSession().getServletContext().getAttribute("user");
        model.addAttribute("user",user);
        return "user/personCenter";
    }

    /**
     * 高媛：跳转到用户信息查询页面
     * @return
     */
    @RequestMapping("toUserInfo")
    public String toUserInfo(){
        return "user/toUserInfo";
    }

    /**
     * 高媛：跳转到页面头的右侧div，能注销用户
     * @return
     */
    @RequestMapping("toGetHeadRight")
    public String toGetHeadRight(){
        return "user/headRight";
    }
    /**
     * 高媛：跳转到个人中心frame的top
     * @return
     */
    @RequestMapping("toHeadPage")
    public String toHeadPage(){
        return "user/toHeadPage";
    }
    /**
     * 高媛：根据用户ID查询用户信息
     * @param userid
     * @return
     */
    @RequestMapping("queryUserInfo")
    public String queryUserInfo(Model model, Integer userid){
        User user=userService.queryUserInfo(userid);
        model.addAttribute("user",user);
        return "user/userInfo";
    }
    /*
    高媛：跳转到查询书架页面
     */
    @RequestMapping("toQueryBookShelf")
    public String toQueryBookShelf(HttpServletRequest request,Model model){
        User user = (User) request.getSession().getServletContext().getAttribute("user");
        model.addAttribute("user",user);
        return "user/showBookShelf";
    }
    /*
    高媛：分页查询书架列表
     */
    @RequestMapping("queryBookShelf")
    public String queryBookShelf(Model model, Integer userid, BookShelfPageUtil<Booklist> page){
        //return userid.toString();
        List<Booklist> list=userService.queryBookShelfByUserid(userid);
//        System.out.println(list);
        BookShelfPageUtil page1= BookShelfPageUtilHelper.pageHelper(list,page.getCpage(),page.getPageSize());
        model.addAttribute("pageInfo",page1);
        return "user/bookShelfList";
    }

    /*
    高媛：跳转到查询历史阅读页面
     */
    @RequestMapping("toQueryBookHistory")
    public String toQueryBookHistory(){
        return "user/showBookHistory";
    }

    /*
    高媛：分页查询历史阅读列表
     */
    @RequestMapping("queryBookHistory")
    public String queryBookHistory(Model model, Integer userid,HttpServletRequest request, BookShelfPageUtil<Booklist> page){
        List<Booklist> list=userService.queryBookHistoryByUserid(userid);
        User user = UserUtil.getUser(request);
        for (Booklist book:list) {
            if (user!=null){
                Bookshelf bs = bookshelfService.queryShelfByUidAndBid(user.getUId(),book.getBlId());
                if (bs!=null){
                    book.setFlag(true);
                }else {
                    book.setFlag(false);
                }
            }else{
                book.setFlag(false);
            }
        }
        BookShelfPageUtil page1=BookShelfPageUtilHelper.pageHelper(list,page.getCpage(),page.getPageSize());
        model.addAttribute("pageInfo",page1);
//        model.addAttribute("bookids",bookids);
        return "user/bookHistoryList";
    }


    /*
    根据书籍ID、章节ID、用户ID查询书籍本章及相关内容，并且跳转页面(连历史记录表)
     */
    @RequestMapping("toReadBookByHistory")
    public String toReadBook(Integer bookid,Integer chapterid,Integer userid,Model model){
//        System.out.println(bookid);
//        System.out.println(chapterid);
//        System.out.println(userid);
        Booklist booklist=userService.queryBookByHistory(bookid,chapterid,userid);
//        System.out.println(booklist);
        model.addAttribute("booklist",booklist);
        return "user/toReadBook";
    }

    /**
     * 高媛：根据书籍ID和用户ID删除历史阅读记录,重定向到查询历史阅读页面
     * @param bookid
     * @param userid
     * @return
     */
    @RequestMapping("toDelBookByHistory")
    public String toDelBookByHistory(Integer bookid,Integer userid){
        userService.toDelBookByHistory(bookid,userid);
        return "redirect:toQueryBookHistory";
    }
    /*
    高媛：根据书籍ID、章节ID、用户ID查询书籍本章及相关内容，并且跳转页面(连书架表)
    */
    @RequestMapping("toReadBookByShelf")
    public String toReadBook1(Integer bookid,Integer chapterid,Integer userid,Model model){
        Booklist booklist=userService.queryBookByShelf(bookid,chapterid,userid);
//        System.out.println(booklist);
        model.addAttribute("booklist",booklist);
        return "user/toReadBook";
    }
    /**
     * 高媛：根据书籍ID和用户ID删除书架书籍,重定向到查询书架列表页面
     * @param bookid
     * @param userid
     * @return
     */
    @RequestMapping("toDelBookByShelf")
    public String toDelBookByShelf(Integer bookid,Integer userid){
        userService.toDelBookByShelf(bookid,userid);
        return "redirect:toQueryBookShelf";
    }
    /**
     * 高媛：批量删除书架书籍
     */
    @RequestMapping("delsBookShelf")
    @ResponseBody
    public void delsBookShelf(String ids,Integer userid){
//        System.out.println(ids);
        List<Integer> list=new ArrayList<>();
        String[] bookids=ids.split(",");
        for (int i = 0; i <bookids.length ; i++) {
            list.add(Integer.parseInt(bookids[i]));
        }
//        System.out.println(list);
        userService.delsBookShelf(list,userid);
    }

    /**
     * 高媛：批量删除历史记录（逻辑删除）
     * @param ids
     * @param userid
     */
    @RequestMapping("delsBookHistory")
    @ResponseBody
    public void delsBookHistory(String ids,Integer userid){
        List<Integer> list=new ArrayList<>();
        String[] bookids=ids.split(",");
        for (int i = 0; i < bookids.length; i++) {
            list.add(Integer.parseInt(bookids[i]));
        }
        userService.delsBookHistory(list,userid);
    }
    /**
     * 高媛：从历史记录加入书架
     */
    @RequestMapping("historyAddToShelf")
    @ResponseBody
    public void historyAddToShelf(Integer userid,Integer bookid){
        userService.historyAddToShelf(userid,bookid);
    }
    /**
     * 高媛：从历史记录批量加入书架
     */
    @RequestMapping("HistoryAddsShelf")
    @ResponseBody
    public void HistoryAddsShelf(String ids,Integer userid){
        List<Integer> list=new ArrayList<>();
        String[] bookids=ids.split(",");
        for (int i = 0; i < bookids.length; i++) {
            list.add(Integer.parseInt(bookids[i]));
        }
        userService.HistoryAddsShelf(list,userid);
    }

    //高媛：批量加入书架去重
    @RequestMapping("getHistoryIds")
    @ResponseBody
    public String getHistoryIds(String ids,HttpServletRequest request){
        User user = UserUtil.getUser(request);
        List<Booklist> list=userService.queryBookHistoryByUserid(user.getUId());
        for (Booklist book:list) {
            if (user!=null){
                Bookshelf bs = bookshelfService.queryShelfByUidAndBid(user.getUId(),book.getBlId());
                if (bs!=null){
                    book.setFlag(true);
                }else {
                    book.setFlag(false);
                }
            }else{
                book.setFlag(false);
            }
        }
        //根据userid所有不在书架上的书的id
        String bids="";
        for (Booklist book:list) {
            if (!book.isFlag()){
                bids+=","+book.getBlId();
            }
        }
        if(bids=="" || bids==null){
            return "";
        }
        String[] tids=ids.split(",");
        String[] tbids=bids.substring(1).split(",");
        System.out.println(bids);
        System.out.println(ids);
        String wantids="";
        for (int i = 0; i < tids.length; i++) {
            for (int j = 0; j < tbids.length; j++) {
                if(tids[i].equals(tbids[j])){
                    wantids+=","+tids[i];
                }
            }
        }
        return wantids.substring(1);
    }
}
